from user import * 
from glue.forum import *
from django.views.decorators.csrf import csrf_exempt
import xmlbase
import logging
# NOTICE: This is the top level module, do not import this file.

def RemoveService(request,sname):
  aut = HasAuthority(request,sname)
  command_error = {}
  if (aut['r'] == False):
      command_error['AUTHORITY'] = 'NO_AUTHORITY'
      return GeneralXMLResponse(request,command_error)
  try:
      data = aut['s']
      try:
        rmtree(CONFIG.SERVICES_PATH+sname)
      except OSError:
        pass
      ServiceCore.delete(data)
      DeleteForum(sname)

      # added by mike for monitor the actions of clients
      cmd.SendMail("DELETE SHOP! ShopName:%s Sub:%s" % (sname,data.local) ,\
        "Shop Deleted! phone: %s, email: %s, website: %s, address: %s" % (data.phone,data.email,data.website,data.address), 
        "clientsdid@auadult.com")

      return GeneralXMLResponse(request,command_error,'Service Removed Successfully')
  except ServiceCore.DoesNotExist:
      command_error['MISC'] = 'Service Does Not Exist'
      return GeneralXMLResponse(request,command_error)

def ResetService(request,name):
    aut = HasAuthority(request,name)
    command_error = {}
    if (aut['r'] == False):
        command_error['AUTHORITY'] = 'NO_AUTHORITY'
        return GeneralXMLResponse(request,command_error)
    try:
        data = ServiceCore.objects.get(name = name)
        if (data.activate == True):
            rmtree(CONFIG.SERVICES_PATH+name)
            InitServiceDir(name)
            return GeneralXMLResponse(request,command_error,'Service Reset Successfully')
        else:
            command_error['MISC'] = 'Service Not Activated'
            return GeneralXMLResponse(request,command_error)
    except ServiceCore.DoesNotExist:
        command_error['MISC'] = 'Service Does Not Exist'
        return GeneralXMLResponse(request,command_error)

def RegisterIconComponent(service):
  data = """<icon name='tmpname' path='default/icon' leftpath='default/icon' size='default'>\
<description>Default Service Icon</description></icon>"""
  xmlbase.CreateNewInfo(service,data,'icon')

def AddService(request):
# Need to build the Error Code and Generate A Replay XML If failed
# If all the info are collected, return a Successful html page.
    s_data = ServiceCore()
    command_error = model_obj_builder(s_data,request.REQUEST,addserv_handler)
    s_data.grade = 1
    s_data.privilege = 'normal'
    s_data.activate = True
    s_data.special_description = ' '
    s_data.special_rate = ' '
    s_data.special_start = ' '
    s_data.special_end = ' '
    s_data.oz_state = ' '
    s_data.region = ' '
    s_data.city = ' '
    rel = ServiceConfig.objects.get(name='default')
    s_data.extend = rel
    Permission.CreateService(request,s_data,command_error)
    
    # added by mike for monitor the actions of clients
    data = s_data
    cmd.SendMail("NEW SHOP! ShopName:%s Sub:%s" % (data.name,data.local) ,\
      "Shop created! phone: %s, email: %s, website: %s, address: %s" % (data.phone,data.email,data.website,data.address), 
      "clientsdid@auadult.com")   

    if command_error:
        service_t = loader.get_template('core/__addservice_fail.xml')
        c = Context({'REQUEST':request.REQUEST,'ERROR':command_error})
        return HttpResponse(service_t.render(c),mimetype = "text/xml")
    else:
        try:
          fail_t = loader.get_template('core/__addservice_conflict.xml')
          old_name_data = ServiceCore.objects.get(name=s_data.name)
          command_error['name'] = "Service Name Already Used"
          return GeneralXMLResponse(request,command_error)
        except ServiceCore.DoesNotExist:
          pass          
        try:
          s_data.full_clean()
          s_data.save()
          sname = s_data.name
          try: 
            InitServiceDir(sname,None) 
          except: #the service folder already exists and mkdir failed
            try:
              fail_t = loader.get_template('core/__addservice_conflict.xml')
              old_name_data = ServiceCore.objects.get(name=s_data.name)
              command_error['name'] = "Service Name Already Used, please change service name"
              return GeneralXMLResponse(request,command_error)
            except ServiceCore.DoesNotExist:
              pass
          RegisterIconComponent(s_data)
          service_t = loader.get_template('core/__addservice_succ.xml')
          c = Context({'REQUEST':request.REQUEST,'service':s_data})
          return HttpResponse(service_t.render(c),mimetype = "text/xml")
        except ValidationError, e:
          service_t = loader.get_template('core/__addservice_fail.xml')
          c = Context({'REQUEST':request.REQUEST,'ERROR':e.message_dict})
          return HttpResponse(service_t.render(c),mimetype = "text/xml")

def ModifyService(request,sname):
    aut = HasAuthority(request,sname)
    command_error = {}
    if (aut['r'] == False):
        command_error['AUTHORITY'] = 'NO_AUTHORITY'
        return GeneralXMLResponse(request,command_error)
    s_data = aut['s']
    # COMMENTED BY MIKE FOR CHANGED THE FIELDS NUMBER
    #command_error = model_obj_builder(s_data,request.REQUEST,mdyserv_handler)
    command_error = model_obj_builder(s_data,request.REQUEST,mdysimple_serv_handler)
    if command_error:
        return GeneralXMLResponse(request,command_error)
    else:
        try:
          #s_data.full_clean() comment this to avoid "Unknow Error, Can Not Save Data"
          s_data.save()
          return GeneralXMLResponse(request,command_error,'Service Info Has Been Updated')
        except ValidationError, e:
          command_error['MISC'] = "Unknow Error, Can Not Save Data"
          return GeneralXMLResponse(request,command_error,'Unknow Error!! Please Check The Input Carefully')

def ModifyDescription(request,sname):
    aut = HasAuthority(request,sname)
    command_error = {}
    if (aut['r'] == False):
        command_error['AUTHORITY'] = 'NO_AUTHORITY'
        return GeneralXMLResponse(request,command_error)
    s_data = aut['s']
    print "just before check field hander is %s " % mdyserv_handler
    command_error = model_obj_builder(s_data,request.REQUEST,mdydesc_handler)
    if command_error:
        print "has error , error is %s" % command_error
        return GeneralXMLResponse(request,command_error)
    else:
        try:
          #s_data.full_clean() comment this to avoid "Unknow Error, Can Not Save Data"
          s_data.save()
          return GeneralXMLResponse(request,command_error,'Service Info Has Been Updated')
        except ValidationError, e:
          command_error['MISC'] = "Unknow Error, Can Not Save Data"
          return GeneralXMLResponse(request,command_error,'Unknow Error!! Please Check The Input Carefully')

def GetServices(request):
# The get service will always provides all the services
    services = ServiceCore.objects.all()
    data_t = loader.get_template('core/__getservices.xml')
    c = Context({'SERVICES':services})
    response = HttpResponse(data_t.render(c),mimetype = "text/xml")
    response['Cache-Control'] = 'no-cache'
    response['Access-Control-Allow-Origin'] = '*'
    response['Access-Control-Allow-Methods'] = 'GET'
    response['Access-Control-Allow-Headers'] = 'X-Requested-With'
    return response

def ActivateService(request,name):
    try:
        data = ServiceCore.objects.get(name = name)
        if (data.activate == True):
            return HttpResponse("Service Already Activated")
        else:
            data.activate = True
            data.save()
            return HttpResponse("Service Activated")
    except ServiceCore.DoesNotExist:
        return HttpResponse("Service Does Not Exist")



